// fast4j - Fast & Agile Service Tools for Java
// Copyright (C) 2007 Alexandre ROMAN
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

// $Id: ServiceContextHolder.java 36 2007-03-27 22:02:40Z alexandre.roman $

package service.api;

/**
 * Holds a {@link ServiceContext} for the current {@link Thread}.
 * @author alexandre.roman
 */
public final class ServiceContextHolder {
    private static final ThreadLocal<ServiceContext> HOLDER = new ThreadLocal<ServiceContext>() {
        protected ServiceContext initialValue() {
            // initialize a new instance
            return new ServiceContext();
        };
    };
    
    /**
     * Gets the {@link ServiceContext} attached to the current {@link Thread}.
     * A new {@link ServiceContext} will be created the first time this method
     * is called.
     * @return a {@link ServiceContext} instance
     */
    public static ServiceContext get() {
        return HOLDER.get();
    }
    
    /**
     * Destroys {@link ServiceContext} instance attached to the current
     * {@link Thread}. This method must be called at the end of the service
     * request to free any resources. This method can be called several times.
     */
    public static void release() {
        HOLDER.remove();
    }
}
